<?php

// TTTTTTTTTTTTTTTTTTTTTTT                  MMMMMMMM               MMMMMMMM                                CCCCCCCCCCCCMMMMMMMM               MMMMMMMM  SSSSSSSSSSSSSSS 
// T:::::::::::::::::::::T                  M:::::::M             M:::::::M                             CCC::::::::::::M:::::::M             M:::::::MSS:::::::::::::::S
// T:::::::::::::::::::::T                  M::::::::M           M::::::::M                           CC:::::::::::::::M::::::::M           M::::::::S:::::SSSSSS::::::S
// T:::::TT:::::::TT:::::T                  M:::::::::M         M:::::::::M                          C:::::CCCCCCCC::::M:::::::::M         M:::::::::S:::::S     SSSSSSS
// TTTTTT  T:::::T  TTTTTppppp   ppppppppp  M::::::::::M       M::::::::::M   eeeeeeeeeeee          C:::::C       CCCCCM::::::::::M       M::::::::::S:::::S            
//         T:::::T       p::::ppp:::::::::p M:::::::::::M     M:::::::::::M ee::::::::::::ee       C:::::C             M:::::::::::M     M:::::::::::S:::::S            
//         T:::::T       p:::::::::::::::::pM:::::::M::::M   M::::M:::::::Me::::::eeeee:::::ee     C:::::C             M:::::::M::::M   M::::M:::::::MS::::SSSS         
//         T:::::T       pp::::::ppppp::::::M::::::M M::::M M::::M M::::::e::::::e     e:::::e     C:::::C             M::::::M M::::M M::::M M::::::M SS::::::SSSSS    
//         T:::::T        p:::::p     p:::::M::::::M  M::::M::::M  M::::::e:::::::eeeee::::::e     C:::::C             M::::::M  M::::M::::M  M::::::M   SSS::::::::SS  
//         T:::::T        p:::::p     p:::::M::::::M   M:::::::M   M::::::e:::::::::::::::::e      C:::::C             M::::::M   M:::::::M   M::::::M      SSSSSS::::S 
//         T:::::T        p:::::p     p:::::M::::::M    M:::::M    M::::::e::::::eeeeeeeeeee       C:::::C             M::::::M    M:::::M    M::::::M           S:::::S
//         T:::::T        p:::::p    p::::::M::::::M     MMMMM     M::::::e:::::::e                 C:::::C       CCCCCM::::::M     MMMMM     M::::::M           S:::::S
//       TT:::::::TT      p:::::ppppp:::::::M::::::M               M::::::e::::::::e                 C:::::CCCCCCCC::::M::::::M               M::::::SSSSSSS     S:::::S
//       T:::::::::T      p::::::::::::::::pM::::::M               M::::::Me::::::::eeeeeeee          CC:::::::::::::::M::::::M               M::::::S::::::SSSSSS:::::S
//       T:::::::::T      p::::::::::::::pp M::::::M               M::::::M ee:::::::::::::e            CCC::::::::::::M::::::M               M::::::S:::::::::::::::SS 
//       TTTTTTTTTTT      p::::::pppppppp   MMMMMMMM               MMMMMMMM   eeeeeeeeeeeeee               CCCCCCCCCCCCMMMMMMMM               MMMMMMMMSSSSSSSSSSSSSSS   
//                        p:::::p                                                                                                                                       
//                        p:::::p                                                                                                                                       
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       ppppppppp                                                                                                                                      

//  _____      __  __         ____ __  __ ____  
// |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
//   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
//   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
//   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2022/05/20
//      |_|                                         | TpMeCMS

declare(strict_types=1);

namespace ImiApp\ApiServer\Api\Controller\store;

use Imi\Db\Db;
use Imi\Server\Http\Route\Annotation\Action;
use Imi\Server\Http\Route\Annotation\Controller;
use Imi\Server\Http\Route\Annotation\Route;
use Psr\Http\Message\ResponseInterface;
use Imi\Aop\Annotation\Inject;
// use Phpben\Imi\Validate\Annotation\Validate;
use Phpben\Imi\Auth\Annotation\Auth;
use ImiApp\ApiServer\Api\Controller\Tpmecms;
use ImiApp\ApiServer\Api\Model\StockWarning;
use Config;

use ImiApp\ApiServer\Api\Model\Store;
use ImiApp\ApiServer\Common\RedisGeo;


use \Imi\Redis\Redis;

use ImiApp\ApiServer\Api\Model\Goodssku;
use ImiApp\ApiServer\Api\Model\GoodsskuPrice;


/**
 * 通知
 * @Auth(name="token",nologin={"*"})
 */
class StoreBean extends Tpmecms
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    /**
     * Geo
     * @Inject("RedisGeo")
     */
    protected $geo;


    // public $store;
    // public $store_id;

    // public function _initialize()
    // {
    //     parent::_initialize();
    //     // $this->store = $this->getStoreByUserId();
    //     // $this->store_id = $this->getStoreId();
    // }

    /**
     * 获取店铺信息-用户id
     *
     * @param int $user_id 用户id
     * @return void
     */
    protected function getStoreByUserId($user_id = null)
    {
        if (!$user_id)
            $user_id = $this->auth->user()->id;
        return Store::dbQuery()->where('user_id', '=', $user_id)->select()->get();
    }




    /**
     * 更新坐标
     * 
     * @param int $id id
     * @param string $lng lng
     * @param string $lat lat
     * @return void
     */
    public function UpdateStoreGeo($id, ?string $lng = null, ?string $lat = null)
    {



        //  $redis = new \Redis();
        // $redis->connect('127.0.0.1', 6379);
        // $redis->auth('8622efe3bada2cc2');
        // var_dump( "Connection to server sucessfully");
        // //设置 redis 字符串数据
        // $redis->set("xiaohe", "Redis tutorial");


        // $redis->geoadd('store',  $lng,$lat, $id);
        //   var_dump('getLastError',  $redis->getLastError());


        // $store = $this->verify_store_id($id);
        if (!$lng || !$lat) {
            $store = Db::name('store')->where('id', '=', $id)->select()->get();
            $lng = $store['lng'];
            $lat = $store['lat'];
        }
        if ($lng && $lat)
            $this->geo->geoadd((float)$lng, (float)$lat, (string)$id, 'store');

        //     $result =  Redis::geoadd('store',  $lng,$lat, $id);
        //     if (!$result) {
        //         var_dump('getLastError', Redis::getLastError());
        //         var_dump($lat, $lng, $id);
        //     }
        // }
    }

    /**
     * 删除坐标
     * 
     * @param int $id id
     * @return void
     */
    public function DelStoreGeo($id)
    {
        $this->geo->del_geo($id, 'store');
    }

    /**
     * 获取坐标列表
     * 
     * @param int $id id
     * @param string $lng lng
     * @param string $lat lat
     * @return void
     */
    public function GetStoreGeoList($lng = null, $lat = null, $m = 50, $unit = 'km', $limit = '10000', $sort = 'ASC', $name = 'store')
    {
        if ($lng && $lat) {

            $list = $this->geo->get_nearby_list($lng, $lat, $m, $unit, $limit, $sort, $name);
            if ($list) {
                $ids = [];
                foreach ($list as $key => $val) {
                    $ids[] = $val[0];
                }
                return $ids;
            }
            // halt($list);
        }
        return;
    }

    /**
     * 初始化空间大小
     *
     * 
     * @param int $id id
     * @return void
     */
    public function InitStoreFilesize($id)
    {
        Db::name('store')->where('id', '=', $id)->update(['now_filesize' => config('store_free_space_size') * 1024]);
    }






    /**
     * 店铺申请成功(待审核)
     * 
     * @param int $id 店铺id
     * @return void
     */
    public function StoreApplySuccessed($id)
    {
        //发送消息提醒?

        // Hook::listen("apply_store_successed",$this->request->param());
    }


    /**
     * 店铺申请通过
     * 
     * @param int $id 店铺id
     * @return void
     */
    public function StoreApplyPass($id)
    {
        \Imi\Log\Log::info('StoreApplyPass' . $id);

        $store = Db::name('store')->where('id', '=', $id)->select()->get();

        //加店铺到期时间
        // $this->IncStoreExpireTime($id, 3600 * 24 * 365); //到期时间

        // //更新坐标
        // $this->UpdateStoreGeo($id);

        //初始化空间大小
        $this->InitStoreFilesize($id);

        //
        // Hook::listen("store_pass",$this->request->param());
    }

    /**
     * 获取店铺到期时间
     * 
     * @param int $id 店铺id
     * @return void
     */
    public function getStoreApplyPassExpireTime($id)
    {
        $store = Db::name('store')->where('id', '=', $id)->select()->get();
        if ($store['expire_time'] < time()) {

            return time() + 3600 * 24 * 365;
        } else {
            return $store['expire_time'] + 3600 * 24 * 365;
        }
    }

    /**
     * 加店铺到期时间
     *
     * @param int $id  店铺id
     * @param int $s 时间秒
     * @return void
     */
    protected function IncStoreExpireTime($id, $s)
    {
        // var_dump($id);
        $store = Db::name('store')->where('id', '=', $id)->select()->get();
        if ($store['expire_time'] < time()) {
            $data['expire_time'] = time() + $s;
            $data['id'] = $id;

            $sql = Db::name('store')->where('id', '=', $id)->update($data);
            // $expire_time = Db::name('store')->where('id', '=', $id)->value('expire_time');
            // \Imi\Log\Log::info('加店铺时间expire_time'.date('Y-m-d H:i:s',$expire_time));
            \Imi\Log\Log::info('加店铺时间' . $id . '__' . $data['expire_time']);
            // exit();
        } else {
            Db::name('store')->where('id', '=', $id)->setFieldInc('expire_time', $s)->update();
        }
    }


    /**
     * 店铺字段
     *
     * @param array $store
     * @return void
     */
    protected function SelfChangeStoreData($store)
    {
        if ($store) {
            $store['area']  = $this->GetAreaName($store['area_id']);
            $store['goodscate_list'] = Db::name('goodscate')->whereIn('id', explode(',', $store['goodscate_ids']))->fieldRaw('name,id')->select()->getArray();
            $store['bbl_expire_time'] = date('Y-m-d', $store['bbl_expire_time']);
        }
        return $store;
    }



    /**
     * 获取店铺二维码
     * 
     * @return string
     */
    public function GetStoreQrcode($id)
    {
        // $qr = new \addons\qrcode\controller\Index;
        // if (empty($this->auth->qr)) {
        // if (1) {
        // $code = $this->EnCode($id);
        // $qr = $qr->get_qr(json_encode(['store_id' => $code]), 'store');
        // Db::name('user')->where('id', $this->auth->user()->id)->update(['qr' => $qr,'invite_code'=>$code]);
        // $this->auth->qr = $qr;
        // $this->auth->save();
        // }else{
        //     $code = $this->auth->invite_code;
        // }
        // return $qr;
        // return $this->success($code, $this->auth->qr);
    }

    /**
     * 添加店铺日志
     *
     * @param int $store_id 店铺日志
     * @return void
     */
    protected function AddStoreLog($store_id)
    {
        // $data['store_id'] = $store_id;
        // $data['status'] = '2'; //类型:1=后台,2=API
        // $data['method'] = $this->request->method();
        // $data['pathinfo'] = $this->request->pathinfo();
        // $data['url'] = $this->request->url();
        // $data['ip'] = $this->request->ip();
        // $data['createtime'] = time();
        // $data['content'] = json_encode($this->request->param(), JSON_UNESCAPED_UNICODE);
        // $data['referer'] = $this->request->header()['referer'];
        // $data['useragent'] = $this->request->header()['user-agent']; //user-agent
        // Db::name('store_log')->insert($data);
    }



    //  _____      __  __         ____ __  __ ____  
    // |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
    //   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
    //   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
    //   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2023/04/11
    //      |_|                                         | TpMeCMS 商品规格




    /**
     * 编辑规格
     *
     * @param array $goods 商品
     * @param array $sku 规格
     * @param string $type 类型 add edit
     * @return void
     */
    protected function editSku($goods, $sku, $type = 'add')
    {
        var_dump('editSku', $sku, $goods['is_sku']);
        if ($goods['is_sku'] == '1') {
            // 多规格
            $this->editMultSku($goods, $sku, $type);
        } else {
            $this->editSimSku($goods, $sku, $type);
        }
        var_dump('editSku over');
    }

    // 根据前端临时 temp_id 获取真实的数据库 id
    private function checkRealIds($newGoodsSkuIds, $allChildrenSku)
    {

        if (!$newGoodsSkuIds)
            return implode(',', $allChildrenSku);
        // if(!$newGoodsSkuIds){
        //     return implode(',', $newIdsArray);
        // }
        // if(!is_array($newGoodsSkuIds))
        $newGoodsSkuIds = explode(',', $newGoodsSkuIds);
        $newIdsArray = [];
        foreach ($newGoodsSkuIds as $id) {
            $newIdsArray[] = $allChildrenSku[$id];
        }
        // var_dump(implode(',', $newIdsArray));
        return implode(',', $newIdsArray);
    }


    // 根据前端临时 temp_id 获取真实的数据库 id
    private function checkRealIds2($newGoodsSkuIds, $allChildrenSku)
    {
        $newIdsArray = [];

        if ($newGoodsSkuIds) {
            $newGoodsSkuIds = explode(',', $newGoodsSkuIds);
            foreach ($newGoodsSkuIds as $id) {
                $newIdsArray[] = $allChildrenSku[$id];
            }
        }

        // var_dump(implode(',', $newIdsArray));
        return implode(',', $newIdsArray);
    }


    /**
     * 添加编辑单规格
     */
    protected function editSimSku($goods, $sku, $type = 'add')
    {
        $params = $this->request->param();
        $params = get_field_arr($params, ['stock', 'stock_warning', 'sn', 'weight', 'price', 'status']);

        // var_dump('params', $params);
        $data = [
            "goods_id" => $goods['id'],
            "stock" => isset($params['stock']) ? $params['stock'] : 1,
            "stock_warning" => isset($params['stock_warning']) && is_numeric($params['stock_warning'])
                ? $params['stock_warning'] : null,
            "sn" => $params['sn'] ?? "",
            "weight" => isset($params['weight']) ? intval($params['weight']) : 0,
            "price" => $params['price'] ?? 0,
            "status" => 'up'
        ];
        var_dump('editSimSku data', $data);


        if ($type == 'add') {
            var_dump('add');
            $goodsSkuPrice = GoodsskuPrice::dbQuery();
            $goodsSkuPrice->insert($data);
        } else {
            // 查询
            $jieguo = GoodsskuPrice::dbQuery()->where('goods_id', '=', $goods['id'])->select()->get();
            if (!$jieguo) {
                // $goodsSkuPrice = GoodsskuPrice::dbQuery();
                GoodsskuPrice::dbQuery()->insert($data);
            } else {
                Db::name('goodssku_price')->where('goods_id', '=', $goods['id'])->update($data);
            }
        }



        // 检测库存预警
        // StockWarning::checkStockWarning($goodsSkuPrice);
    }


    /**
     * 添加编辑多规格
     */
    protected function editMultSku($goods, $sku, $type = 'add')
    {
        $skuList = json_decode($sku['listJson'], true);
        $skuPrice = json_decode($sku['priceJson'], true);
        var_dump('priceJson', $sku['priceJson']);
        if (count($skuList) < 1) {
            return $this->error('请填写规格列表');
        }
        foreach ($skuList as $key => $sku) {
            if (count($sku['children']) <= 0) {
                return $this->error('主规格至少要有一个子规格');
            }

            // 验证子规格不能为空
            foreach ($sku['children'] as $k => $child) {
                if (!isset($child['name']) || empty(trim($child['name']))) {
                    return $this->error('子规格不能为空');
                }
            }
        }

        if (count($skuPrice) < 1) {
            return $this->error('请填写规格价格');
        }
        var_dump('skuPrice1', $skuPrice);


        foreach ($skuPrice as &$price) {
            if (empty($price['price']) || $price['price'] == 0) {
                return $this->error('请填写规格价格');
            }
            if ($price['stock'] === '') {
                return $this->error('请填写规格库存');
            }
            if (empty($price['weight'])) {
                $price['weight'] = 0;
            }
        }

        var_dump('skuPrice2', $skuPrice);


        // 编辑保存规格项
        $allChildrenSku = $this->saveSkuList($goods, $skuList, $type);

        if ($type == 'add') {
            // 创建新产品，添加规格列表和规格价格
            foreach ($skuPrice as $s3 => &$k3) {


                $k3['goods_sku_ids'] = $this->checkRealIds($k3['goods_sku_temp_ids'], $allChildrenSku);
                $k3['goods_id'] = $goods['id'];
                $k3['goods_sku_text'] = $k3['goods_sku_text']; //implode(',', $k3['goods_sku_text']);
                $k3['weigh'] = isset($k3['weigh']) ? intval($k3['weigh']) : 0;
                $k3['weight'] = isset($k3['weight']) ? $k3['weight'] : 0;
                $k3['createtime'] = time();
                $k3['updatetime'] = time();

                // var_dump($k3);
                unset($k3['name']);
                unset($k3['id']);
                unset($k3['temp_id']);      // 前端临时 id
                unset($k3['goods_sku_temp_ids']);       // 前端临时规格 id,查找真实 id 用
            }

            $res = GoodsskuPrice::dbQuery()->batchInsert($skuPrice);

            // 检测库存预警
            (new StockWarning)->checkAllStockWarning($res, 'add');
        } else {
            // 编辑旧商品，先删除老的不用的 skuPrice

            $oldSkuPriceIds = array_column($skuPrice, 'id');

            // 删除当前商品老的除了在基础上修改的skuPrice

            $要删除的sukprice = GoodsskuPrice::dbQuery()->where('goods_id', '=', $goods['id'])
                ->where('id', 'not in', $oldSkuPriceIds)->column('id');
            var_dump('oldSkuPriceIds', $oldSkuPriceIds, '要删除的sukprice', $要删除的sukprice);

            GoodsskuPrice::dbQuery()->where('goods_id', '=', $goods['id'])
                ->where('id', 'not in', $oldSkuPriceIds)->delete();

            // 删除失效的库存预警记录
            (new StockWarning)->delNotStockWarning($oldSkuPriceIds, $goods['id']);

            foreach ($skuPrice as $s3 => &$k3) {
                var_dump('编辑商品库存价格', $k3['goods_sku_temp_ids'], $allChildrenSku);

                if (isset($k3['goods_sku_temp_ids']) && $k3['goods_sku_temp_ids'])
                    $data['goods_sku_ids'] = $this->checkRealIds2($k3['goods_sku_temp_ids'], $allChildrenSku);
                $data['goods_id'] = $goods['id'];
                $data['goods_sku_text'] = $k3['goods_sku_text']; //implode(',', $k3['goods_sku_text']);
                $data['weigh'] = isset($k3['weigh']) ? $k3['weigh'] : 0;
                $data['image'] = $k3['image'];
                $data['stock'] = $k3['stock'];
                $data['stock_warning'] = $k3['stock_warning'];
                $data['sn'] = $k3['sn'];
                $data['weight'] = isset($k3['weight']) ? $k3['weight'] : 0;
                $data['price'] = $k3['price'];
                $data['status'] = $k3['status'];
                $data['createtime'] = time();
                $data['updatetime'] = time();

                if ($k3['id']) {
                    // 编辑
                    $goodsSkuPrice = GoodsskuPrice::dbQuery()->where('id', '=', $k3['id'])->update($data);
                } else {

                    // 新增数据
                    // $goodsSkuPrice = new GoodsskuPrice();
                    $goodsSkuPrice = GoodsskuPrice::dbQuery()->insert($data);
                }

                if ($goodsSkuPrice) {
                    // $goodsSkuPrice->save($data);

                    // 检测库存预警
                    // $this->checkStockWarning($goodsSkuPrice);
                    // StockWarning::checkStockWarning($goodsSkuPrice);
                }
            }
        }
    }



    // 差异更新 规格规格项（多的删除，少的添加）
    protected function saveSkuList($goods, $skuList, $type = 'add')
    {
        $allChildrenSku = [];
        if ($type == 'edit') {
            // 删除无用老规格
            // 拿出需要更新的老规格
            $oldSkuIds = [];
            foreach ($skuList as $key => $sku) {
                $oldSkuIds[] = $sku['id'];

                $childSkuIds = [];
                if ($sku['children']) {
                    // 子项 id
                    $childSkuIds = array_column($sku['children'], 'id');
                }

                $oldSkuIds = array_merge($oldSkuIds, $childSkuIds);
                $oldSkuIds = array_unique($oldSkuIds);
            }

            // 删除老的除了在基础上修改的规格项
            Goodssku::dbQuery()->where('goods_id', '=', $goods['id'])->where('id', 'not in', $oldSkuIds)->delete();
        }

        // 
        foreach ($skuList as $s1 => &$k1) {
            //添加主规格
            if ($k1['id']) {
                // 编辑
                Goodssku::dbQuery()->where('id', '=', $k1['id'])->update([
                    'name' => $k1['name'],
                ]);

                $skuId[$s1] = $k1['id'];
            } else {
                // 新增
                $skuId[$s1] = Goodssku::dbQuery()->insert([
                    'name' => $k1['name'],
                    'pid' => 0,
                    'image' => $k1['image'],
                    'goods_id' => $goods['id']
                ])->getLastInsertId();
            }
            $k1['id'] = $skuId[$s1];
            foreach ($k1['children'] as $s2 => &$k2) {
                if ($k2['id']) {
                    // 编辑
                    Goodssku::dbQuery()->where('id', '=', $k2['id'])->update([
                        'name' => $k2['name'],
                        'image' => $k2['image'],
                    ]);

                    $skuChildrenId[$s1][$s2] = $k2['id'];
                } else {
                    $skuChildrenId[$s1][$s2] = Goodssku::dbQuery()->insert([
                        'name' => $k2['name'],
                        'pid' => $k1['id'],
                        'image' => $k2['image'],
                        'goods_id' => $goods['id']
                    ])->getLastInsertId();
                }

                $allChildrenSku[$k2['temp_id']] = $skuChildrenId[$s1][$s2];
                $k2['id'] = $skuChildrenId[$s1][$s2];
                $k2['pid'] = $k1['id'];
            }
        }

        var_dump('635 allChildrenSku', $allChildrenSku);
        return $allChildrenSku;
    }

    //  _____      __  __         ____ __  __ ____  
    // |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
    //   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
    //   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
    //   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2023/04/11
    //      |_|                                         | TpMeCMS 商品规格



    /**
     * 支付店铺保证金订单
     *
     * @param array $store_caorder 店铺保证金订单
     * @param integer $pay_type 支付类型:1=微信,2=支付宝,3=钱包,9=其他
     * @return void
     */
    protected function PayStoreSuretyorder($store_suret_order, $pay_type = '3', $status)
    {
        //获取店铺保证金支付订单
        $data['order_id'] = $store_suret_order['id'];
        $data['user_id'] = $store_suret_order['user_id'];
        $data['store_id'] = $store_suret_order['store_id'];
        $order_data = Db::name('store_pay_order')->whereEx($data)->select()->get();

        if ($order_data) {
            if ($order_data['pay_status'] == '2')
                return $this->error('您已支付保证金');
        } else {
            $order_data['pay_type'] = $pay_type;
            $order_data['money'] = $store_suret_order['money'];
            $order_data['order_id'] = $store_suret_order['id'];
            $order_data['order_status'] = '7'; //7=保证金
            $order_data['pay_status'] = '1'; //支付状态:1=待支付,2=已支付,3=已退款,4=已超时

            $order_data['role_status'] = '2'; //角色:1=用户,2=店铺
            $order_data['store_id'] = $store_suret_order['store_id']; //店铺id
            $order_data['time'] = time();
            $order_data['user_id'] = $store_suret_order['user_id'];
            $order_data['id'] = Db::name('store_pay_order')->insert($order_data)->getLastInsertId();
        }


        switch ($pay_type) {
            case '1':
                return $this->error('支付方式暂未开通');
                break;
            case '2':
                return $this->error('支付方式暂未开通');
                break;
            case '3':
                //判断用户的钱包够不够 
                if ($order_data['money'] > $this->store->money) {
                    return $this->error('店铺钱包余额不足', $order_data['money'], CODE_店铺余额不足);
                }
                $this->DecStoreMoney($order_data['store_id'], $order_data['money'], '店铺支付保证金费用', CODE_店铺保支付证金, $order_data['id']);

                $this->StoreSuretPaySuccessed($order_data['id'], $status, $order_data, $order_data['store_id']);
                return $this->success('店铺钱包支付成功', $order_data, 3);
                break;
            default:
                return $this->error('没有该支付方式', $order_data);
                break;
        }
    }


    /**
     * 支付店铺认证订单
     *
     * @param array $store_caorder 店铺认证订单
     * @param integer $pay_type 支付类型:1=微信,2=支付宝,3=钱包,9=其他
     * @return void
     */
    protected function PayStoreCaorder($store_caorder, $pay_type = '3')
    {
        //获取店铺认证支付订单
        $data['order_id'] = $store_caorder['id'];
        $data['user_id'] = $store_caorder['user_id'];
        $order_data = Db::name('pay_order')->whereEx($data)->select()->get();

        if ($order_data) {
            if ($order_data['pay_status'] == '2')
                return $this->error('您已支付认证');
        } else {
            $order_data['pay_type'] = $pay_type;
            $order_data['money'] = $store_caorder['money'];
            $order_data['order_id'] = $store_caorder['id'];
            $order_data['order_status'] = '4'; //订单类型:1=现金购物,2=购买积分,3=购买贝壳,4=店铺定金,5=其他
            $order_data['pay_status'] = '1'; //支付状态:1=待支付,2=已支付,3=已退款,4=已超时

            $order_data['role_status'] = '1'; //角色:1=用户,2=店铺
            $order_data['time'] = time();
            $order_data['user_id'] = $store_caorder['user_id'];
            $order_data['id'] = Db::name('pay_order')->insert($order_data)->getLastInsertId();
        }

        switch ($pay_type) {
            case '1':
                return $this->error('支付方式暂未开通');
                break;
            case '2':
                return $this->error('支付方式暂未开通');
                break;
            case '3':
                //判断用户的钱包够不够 
                if ($order_data['money'] > $this->auth->money()) {
                    return $this->error('钱包余额不足', $order_data['money'], CODE_余额不足);
                }
                $this->DecUserMoney($order_data['user_id'], $order_data['money'], '店铺认证费用', CODE_店铺认证费用, $order_data['id']);

                $this->StoreCaPaySuccessed($order_data['id'], $pay_type, $order_data, $store_caorder['store_id']);
                return $this->success('钱包支付成功', $order_data['money'], 3);
                break;
            default:
                return $this->error('没有该支付方式');
                break;
        }
    }


    /**
     * 店铺认证支付成功
     *
     * @param string $id
     * @return void
     */
    protected function StoreSuretPaySuccessed($id, $pay_type, $order_data, $store_id)
    {
        //order_status 订单类型:1=现金购物,2=购买积分,3=购买贝壳,4=店铺定金,5=其他
        Db::name('store_pay_order')->where('id', '=', $id)->update(['pay_status' => '2', 'pay_type' => $pay_type, 'pay_time' => time(), 'pay_money' => $order_data['money'] * 100]);
        //修改认证订单
        Db::name('store_surety_order')->where('id', '=', $order_data['order_id'])->update(['pay_status' => '2', 'pay_type' => $pay_type, 'pay_money' => $order_data['money'] * 100]);
        $store = Db::name('store')->where('id', '=', $store_id)->find();
        var_dump('店铺id' . $store_id, $store['act_surety'], $store['surety'], $order_data['money'], $pay_type);


        switch ($pay_type) {
            case '1':
                Db::name('store')->where('id', '=', $store_id)->setFieldInc('surety', (float) $order_data['money'])->update();
                break;
            case '2':
                Db::name('store')->where('id', '=', $store_id)->setFieldInc('act_surety', (float) $order_data['money'])->update();
                break;
            default:
                # code...
                break;
        }
    }

    /**
     * 判断店铺活动保证金
     *
     * @param int $store_id 店铺id
     * @param float $act_surety 需要多少
     * @return void
     */
    protected function judge_act_surety($store_id, $act_surety)
    {
        $store_act_surety = Db::name('store')->where('id', '=', $store_id)->value('act_surety');
        if ($store_act_surety >= $act_surety) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 判断店铺保证金
     *
     * @param int $store_id 店铺id
     * @param float $surety 需要多少
     * @return void
     */
    protected function judge_surety($store_id, $surety)
    {
        $store_surety = Db::name('store')->where('id', '=', $store_id)->value('surety');
        if ($store_surety >= $surety) {
            return true;
        } else {
            return false;
        }
    }







    /**
     * 店铺认证支付成功
     *
     * @param string $id
     * @return void
     */
    protected function StoreCaPaySuccessed($id, $pay_type, $order_data, $store_id)
    {
        Db::name('pay_order')->where('id', '=', $id)->update(['pay_status' => '2', 'pay_type' => $pay_type, 'pay_time' => time(), 'pay_money' => $order_data['money'] * 100]);
        //修改认证订单
        Db::name('store_caorder')->where('id', '=', $order_data['order_id'])->update(['pay_status' => '2', 'pay_type' => $pay_type, 'pay_money' => $order_data['money'] * 100]);
        $store = Db::name('store')->where('id', '=', $store_id)->find();
        if ($store['expire_time'] > time()) {
            $expire_time = $store['expire_time'] + 3600 * 24 * 365;
        } else {
            $expire_time = time() + 3600 * 24 * 365;
        }
        Db::name('store')->where('id', '=', $store_id)->where('apply_status', '<>', '2')->update(['payca_status' => '2', 'apply_status' => '1', 'expire_time' => $expire_time]);
    }


    /**
     * 店铺续费支付成功
     *
     * @param string $id
     * @return void
     */
    protected function StoreKeepCaPaySuccessed($id, $pay_type, $order_data, $store_id)
    {
        Db::name('pay_order')->where('id', '=', $id)->update(['pay_status' => '2', 'pay_type' => $pay_type, 'pay_time' => time(), 'pay_money' => $order_data['money'] * 100]);
        //修改认证订单
        Db::name('store_caorder')->where('id', '=', $order_data['order_id'])->update(['pay_status' => '2', 'pay_type' => $pay_type, 'pay_money' => $order_data['money'] * 100]);
        // $store = Db::name('store')->where('id', '=', $store_id)->find();
        // if($store['expire_time']>time()){
        //     $expire_time = $store['expire_time'] +3600*24*365;
        // }else{
        //     $expire_time = time() +3600*24*365;
        // }
        $this->IncStoreExpireTime($store_id, 3600 * 24 * 365);
    }





    /**
     * 续费店铺认证订单
     *
     * @param array $store_caorder store_caorder
     * @param integer $pay_type 支付类型:1=微信,2=支付宝,3=钱包,9=其他
     * @return void
     */
    protected function KeepPayStoreCaorder($store_caorder, $pay_type = '3')
    {

        //获取店铺认证支付订单
        $data['order_id'] = $store_caorder['id'];
        $data['user_id'] = $store_caorder['user_id'];
        $order_data = Db::name('pay_order')->whereEx($data)->select()->get();

        if ($order_data) {
            if ($order_data['pay_status'] == '2')
                return $this->error('您已支付认证');
        } else {
            $order_data['pay_type'] = $pay_type;
            $order_data['money'] = $store_caorder['money'];
            $order_data['order_id'] = $store_caorder['id'];
            $order_data['order_status'] = '4'; //订单类型:1=现金购物,2=购买积分,3=购买贝壳,4=店铺定金,5=其他
            $order_data['pay_status'] = '1'; //支付状态:1=待支付,2=已支付,3=已退款,4=已超时

            $order_data['role_status'] = '1'; //角色:1=用户,2=店铺
            $order_data['time'] = time();
            $order_data['user_id'] = $store_caorder['user_id'];
            $order_data['id'] = Db::name('pay_order')->insert($order_data)->getLastInsertId();
        }

        switch ($pay_type) {
            case '1':
                return $this->error('支付方式暂未开通');
                break;
            case '2':
                return $this->error('支付方式暂未开通');
                break;
            case '3':
                //判断用户的钱包够不够 
                if ($order_data['money'] > $this->auth->money()) {
                    return $this->error('钱包余额不足', $this->auth->money(), CODE_余额不足);
                }
                $this->DecUserMoney($order_data['user_id'], $order_data['money'], '店铺续费费用', CODE_店铺认证费用, $order_data['id']);

                $this->StoreKeepCaPaySuccessed($order_data['id'], $pay_type, $order_data, $store_caorder['store_id']);
                return $this->success('钱包支付成功', null, 3);
                break;
            default:
                return $this->error('没有该支付方式');
                break;
        }
    }
}
